import { defineStore } from 'pinia'
import { getUser } from '@/api/user'
import { removeToken } from '@/utils/token'
import { reactive, ref } from 'vue'
export const useTestStore = defineStore('user', () => {
  let state = reactive({
    userInfo: {},
    permissions: [],
  })
  const getters = {
    userId() {
      return state.userInfo?.id
    },
    name() {
      return state.userInfo?.name
    },
    avatar() {
      return state.userInfo?.avatar
    },
    role() {
      return state.userInfo?.role || []
    },
    getPermissions() {
      return state.userInfo?.role || []
    },
  }
  const actions = {
    async getUserInfo() {
      try {
        const res = await getUser()
        if (res.code === 0) {
          const { id, name, avatar, role } = res.data
          state.userInfo = { id, name, avatar, role }
          return Promise.resolve(res.data)
        } else {
          return Promise.reject(res.message)
        }
      } catch (error) {
        console.error(error)
        return Promise.reject(error.message)
      }
    },
    logout() {
      removeToken()
      state.userInfo = {}
    },
    setUserInfo(newUserInfo = {}) {
      state.userInfo = { ...state.userInfo, ...newUserInfo }
    },
  }
  return {
    state,
    getters,
    actions,
  }
})
